package com.zl.learning.db.sqlite.core;


import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by zhaolei on 2017/5/23.
 */
public class SingleColumnRowMapper<T> implements RowMapper<T> {
    private Class<?> requiredType;

    public SingleColumnRowMapper(Class<T> requiredType) {
        setRequiredType(requiredType);
    }


    @Override
    public T mapRow(ResultSet rs) throws SQLException {
        Object result = getColumnValue(rs, 1, this.requiredType);
        if (result != null && this.requiredType != null && !this.requiredType.isInstance(result)) {
            try {
                return (T) result;
            }
            catch (IllegalArgumentException ex) {
                throw ex;
            }
        }
        return (T) result;
    }

    public void setRequiredType(Class<T> requiredType) {
        this.requiredType = requiredType;
    }

    protected Object getColumnValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
        if (requiredType != null) {
            return JdbcUtils.getResultSetValue(rs, index, requiredType);
        }
        else {
            return getColumnValue(rs, index);
        }
    }

    protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index);
    }

    public static <T> SingleColumnRowMapper<T> newInstance(Class<T> requiredType) {
        return new SingleColumnRowMapper<T>(requiredType);
    }

}
